document.addEventListener('DOMContentLoaded', () => {
    const loginForm = document.getElementById('loginForm');
    const alertMessage = document.getElementById('alertMessage');
    const passwordToggle = document.getElementById('passwordToggle');
    const passwordInput = document.getElementById('password');
    const usernameInput = document.getElementById('username');
    const rememberMe = document.getElementById('rememberMe');
    
    // 密码可见性切换
    passwordToggle.addEventListener('click', () => {
        const type = passwordInput.type === 'password' ? 'text' : 'password';
        passwordInput.type = type;
        passwordToggle.className = `fas ${type === 'password' ? 'fa-eye' : 'fa-eye-slash'} password-toggle`;
    });

    // 显示提示消息的函数
    function showMessage(message, type) {
        alertMessage.textContent = message;
        alertMessage.className = 'alert-message ' + type;
        
        if (type === 'error') {
            alertMessage.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
        } else {
            alertMessage.innerHTML = `<i class="fas fa-check-circle"></i> ${message}`;
        }
        
        // 5秒后自动隐藏消息
        setTimeout(() => {
            alertMessage.style.display = 'none';
        }, 5000);
    }
    
    // 重置表单状态
    function resetFormStatus() {
        document.querySelectorAll('.input-icon').forEach(input => {
            input.classList.remove('error');
        });
        alertMessage.style.display = 'none';
    }
    
    // 检查是否可以自动登录
    function checkAutoLogin() {
        const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
        const remembered = localStorage.getItem('rememberMe') === 'true';
        const savedUsername = localStorage.getItem('savedUsername');
        const savedPassword = localStorage.getItem('savedPassword');
        
        if (isLoggedIn && remembered && savedUsername && savedPassword) {
            // 自动填充表单
            usernameInput.value = savedUsername;
            passwordInput.value = savedPassword;
            rememberMe.checked = true;
            
            // 自动提交表单
            const button = document.querySelector('.btn-login');
            button.classList.add('loading');
            
            setTimeout(() => {
                handleLoginSuccess(button);
            }, 500);
            
            return true;
        }
        return false;
    }

    // 页面加载时检查自动登录
    if (checkAutoLogin()) {
        showMessage('正在自动登录...', 'success');
    }
    
    // 检查保存的登录信息
    function checkSavedCredentials() {
        const savedUsername = localStorage.getItem('savedUsername');
        const savedPassword = localStorage.getItem('savedPassword');
        const remembered = localStorage.getItem('rememberMe') === 'true';
        
        if (remembered && savedUsername && savedPassword) {
            usernameInput.value = savedUsername;
            passwordInput.value = savedPassword;
            rememberMe.checked = true;
        }
    }
    
    // 保存登录信息
    function saveCredentials() {
        if (rememberMe.checked) {
            localStorage.setItem('savedUsername', usernameInput.value);
            localStorage.setItem('savedPassword', passwordInput.value);
            localStorage.setItem('rememberMe', 'true');
        } else {
            localStorage.removeItem('savedUsername');
            localStorage.removeItem('savedPassword');
            localStorage.removeItem('rememberMe');
        }
    }

    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        resetFormStatus();
        
        const username = usernameInput.value;
        const password = passwordInput.value;
        const button = document.querySelector('.btn-login');
        
        if (!validateInput(usernameInput, passwordInput)) return;
        
        button.classList.add('loading');
        
        try {
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            if (username === 'admin' && password === 'admin') {
                // 保存登录信息
                saveCredentials();
                handleLoginSuccess(button);
            } else {
                handleLoginFailure(button);
            }
        } catch (error) {
            showMessage('登录过程中发生错误，请重试', 'error');
            button.classList.remove('loading');
        }
    });
    
    function validateInput(username, password) {
        if (!username.value.trim()) {
            username.parentElement.classList.add('error');
            showMessage('请输入用户名', 'error');
            return false;
        }
        
        if (!password.value.trim()) {
            password.parentElement.classList.add('error');
            showMessage('请输入密码', 'error');
            return false;
        }
        
        return true;
    }
    
    function handleLoginSuccess(button) {
        button.classList.remove('loading');
        button.innerHTML = '<i class="fas fa-check"></i> 登录成功';
        button.style.background = '#2ecc71';
        showMessage('登录成功，正在跳转...', 'success');
        
        // 保存登录状态和凭据
        localStorage.setItem('isLoggedIn', 'true');
        if (rememberMe.checked) {
            localStorage.setItem('savedUsername', usernameInput.value);
            localStorage.setItem('savedPassword', passwordInput.value);
            localStorage.setItem('rememberMe', 'true');
        }
        
        // 延迟跳转
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1000);
    }
    
    function handleLoginFailure(button) {
        button.classList.remove('loading');
        button.innerHTML = '<i class="fas fa-times"></i> 登录失败';
        button.style.background = '#e74c3c';
        showMessage('用户名或密码错误', 'error');
        loginForm.classList.add('shake');
        
        // 清除登录状态
        localStorage.removeItem('isLoggedIn');
        
        setTimeout(() => {
            loginForm.classList.remove('shake');
            button.innerHTML = '<span>登录系统</span><i class="fas fa-arrow-right"></i>';
            button.style.background = '';
        }, 1000);
    }
    
    // 添加退出登录功能
    window.handleLogout = function() {
        localStorage.removeItem('isLoggedIn');
        if (!rememberMe.checked) {
            localStorage.removeItem('savedUsername');
            localStorage.removeItem('savedPassword');
            localStorage.removeItem('rememberMe');
        }
        window.location.href = 'login.html';
    };
    
    // 输入框焦点效果
    document.querySelectorAll('.input-icon input').forEach(input => {
        input.addEventListener('focus', () => {
            resetFormStatus();
            input.parentElement.classList.add('focused');
        });
        
        input.addEventListener('blur', () => {
            if (!input.value) {
                input.parentElement.classList.remove('focused');
            }
        });
        
        // 输入时移除错误状态
        input.addEventListener('input', () => {
            input.parentElement.classList.remove('error');
            if (alertMessage.classList.contains('error')) {
                alertMessage.style.display = 'none';
            }
        });
    });
});

// 添加输入动画效果
document.querySelectorAll('.input-icon input').forEach(input => {
    input.addEventListener('focus', () => {
        input.parentElement.classList.add('focused');
    });
    
    input.addEventListener('blur', () => {
        if (!input.value) {
            input.parentElement.classList.remove('focused');
        }
    });
}); 